package com.sjb.cp.api.imageSearch.sub;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.sjb.cp.exception.BusinessException;
import com.sjb.cp.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpPost;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:sjb
 * @CreateTime:2025-01-26
 * @Description: 根据链接以图搜图
 * @Version：1.0
 */
@Slf4j
public class GetImagePageUrlApi {

    /**
     * 以图搜图 使用链接url
     * @param imgUrl
     * @return
     */
    public static String getImagePageUrl(String imgUrl) {

        //1、准备请求参数
        Map<String, Object> formData = new HashMap<>();
        formData.put("image", imgUrl);
        formData.put("tn", "pc");
        formData.put("from", "pc");
        formData.put("image_source", "PC_UPLOAD_URL");

        //当前时间戳
        long uptime = System.currentTimeMillis();
        // 请求地址
        String url = "https://graph.baidu.com/upload?uptime=" + uptime;

        //2、发送请求
        String searchResultUrl = null;
        try {
            HttpResponse response = HttpRequest.post(url)
                    .form(formData)
                    .timeout(3000)
                    .execute();

            // 判断响应状态
            if (HttpStatus.HTTP_OK != response.getStatus()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口调用失败");
            }
            // 解析响应
            String body = response.body();
            Map<String,Object> result = JSONUtil.toBean(body, Map.class);
            // 3. 处理响应结果
            if (result == null || !Integer.valueOf(0).equals(result.get("status"))) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口调用失败");
            }

            Map<String,Object> data = (Map<String,Object>)result.get("data");
            String rawUrl = (String) data.get("url");
            // 对url进行解码
            searchResultUrl = URLUtil.decode(rawUrl, StandardCharsets.UTF_8);
            if (searchResultUrl == null){
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"未返回有效结果");
            }
        } catch (Exception e) {
            log.error("搜索失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "搜索失败");
        }
        return searchResultUrl;
    }

    public static void main(String[] args) {
        // 测试以图搜图功能
        String imageUrl = "https://www.codefather.cn/logo.png";
        String result = getImagePageUrl(imageUrl);
        System.out.println("搜索成功，结果 URL：" + result);
    }
}
